package com.renjian.screens;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;

import com.renjian.RenJian;
import com.renjian.model.KeyMap;
import com.renjian.resource.RenJianResource;
import com.renjian.util.Constant;
import com.renjian.util.HttpConnectionUtil;

public class TestScreen extends MainScreen implements RenJianResource, Constant {

	private MenuItem menuUserTimeLine = new MenuItem(_resource
			.getString(MENUUSERTIMELINE), 0, 100) {

		public void run() {
			RenJian theApp = (RenJian) getApplication();
			theApp.pushScreen(new UserTimeLineScreen());
		}
	};

	public TestScreen() {
		logger.log("test screen in process.");
		try {
			hack.checkWifi(_resource, this);
			setupUi();
		} catch (IOException e) {
			logger.log(e.getMessage());
		}
		logger.log("test screen initialed.");
	}

	private void setupUi() throws IOException {
		String url = _resource.getString(VERIFY).trim();
		String username = _resource.getString(USERNAME).trim();
		String password = _resource.getString(PASSWORD).trim();

		logger.log("url:" + url + ",uname:" + username + ",password:"
				+ password);

		KeyMap[] keys = new KeyMap[1];
		KeyMap[] paras = new KeyMap[0];
		String auth = hack.base64Encrypt(username + ":" + password);
		// String auth = username + ":" + password;
		logger.log("auth:" + auth);

		keys[0] = new KeyMap();// page=1&since_id=361379&count=2

		keys[0].setKey("Authorization");
		keys[0].setVal("Basic " + auth);

		if (!new HttpConnectionUtil() {
			public boolean process(byte[] ch) {
				String ret = null;
				try {
					ret = new String(ch, "utf-8");
					try {
						hack.user.xmlToUser(ret);
						logger.log(hack.user.toString());
					} catch (Exception e) {
						logger.log(e.getMessage());
					}
				} catch (UnsupportedEncodingException e) {
					logger.log(e.getMessage());
				}
				logger.log("hpx success:" + ret);
				add(new RichTextField(hack.user.toString()));
				return true;
			}
		}.processRequest(url, paras, keys)) {
			logger.log("failed");
			add(new LabelField("failed"));
			return;
		}
		addMenuItem(menuUserTimeLine);

	}

}
